package com.doge.walknovel.business.home.genres.genres

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.doge.walknovel.api.model.StrategyChildInfo
import com.doge.walknovel.business.home.genres.TabHelper
import com.doge.walknovel.core.BaseFragment
import com.doge.wnpro.databinding.FragmentGenresTabBinding

class GenresTabFragment : BaseFragment() {
    private var innerBinding: FragmentGenresTabBinding? = null
    private val binding get() = innerBinding!!
    private val viewModel: GenresTabViewModel by viewModels { GenresTabViewModelFactory() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding =
            innerBinding ?: FragmentGenresTabBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.tabs.observe(viewLifecycleOwner) {
            setupViewPager(it)
        }
        viewModel.initializeTabs()
    }

    private fun setupViewPager(tabs: List<StrategyChildInfo>) {
        binding.viewPager.offscreenPageLimit = 2
        binding.viewPager.adapter = RankAdapter(this, tabs)
        TabHelper.setupCustomTab(binding.tab, binding.viewPager, tabs)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.viewPager.adapter = null
        innerBinding = null
    }

    class RankAdapter(val fragment: Fragment, private val tabs: List<StrategyChildInfo>) :
        androidx.viewpager2.adapter.FragmentStateAdapter(fragment) {

        override fun getItemCount(): Int = tabs.size

        override fun createFragment(position: Int): Fragment {
            if (position < 0 || position >= tabs.size) return BaseFragment()
            return GenresCellFragment.newInstance(tabs[position].tabId!!)
        }
    }

    companion object {
        fun newInstance(): GenresTabFragment {
            return GenresTabFragment()
        }
    }
}